class GitOperate {
  constructor(config = {}) {
    this.init(config);
  }
  init(config = {}) {
    // 设置 Gitee 仓库信息和目录路径
    this.username = config.username;
    this.repo = config.repo;
    this.accessToken = config.accessToken;
    this.branchName = config.branchName || "master";
    this.apiUrl = "https://gitee.com/api/v5/repos/";
    this.dirPath = config.dirPath;
  }
  async getImg() {
    try {
      const response = await fetch(
        `${this.apiUrl}${this.username}/${this.repo}/contents/${this.dirPath}`,
        {
          headers: {
            Authorization: `token ${this.accessToken}`,
          },
        }
      );

      if (!response.ok) {
        throw new Error("获取图片列表失败");
      }

      const data = await response.json();

      // 筛选出图片文件
      const imageFiles = data.filter(
        (file) =>
          file.type === "file" && file.name.match(/\.(jpg|jpeg|png|gif)$/i)
      );

      return imageFiles;
    } catch (error) {
      console.error(error);
      throw error;
    }
  }

  async uploadToGitee(base64Data,isShowToast = true) {
    try {
      const formData = new FormData();
      formData.append("content", base64Data);
      formData.append("access_token", this.accessToken);
      formData.append("message", "上传图片");

      const timeStamp = new Date().getTime();
      if(isShowToast){
        Toast.showLoading("正在上传");
      }
      const response = await fetch(
        `${this.apiUrl}${this.username}/${this.repo}/contents/${this.dirPath}/${timeStamp}.jpg`,
        {
          method: "POST",
          body: formData,
        }
      );
      if(isShowToast){
        Toast.hide();
      }
      if (!response.ok) {
        throw new Error("上传图片失败");
      }

      const data = await response.json();
      if(isShowToast){
        Toast.showToast("图片上传成功！");
      }
      return data.content.download_url;
    } catch (error) {
      console.error(error);
      Toast.showToast("图片上传失败！");
      throw error;
    }
  }

  async deleteImg(fileName, sha, cb) {
    try {
      Toast.showLoading("删除中……");
      const response = await fetch(
        `${this.apiUrl}${this.username}/${this.repo}/contents/${this.dirPath}/${fileName}?access_token=${this.accessToken}&ref=${this.branchName}`,
        {
          method: "DELETE",
          headers: {
            "Content-Type": "application/json;charset=utf-8",
          },
          body: JSON.stringify({
            message: "删除图片",
            sha,
            prune: true,
          }),
        }
      );

      if (!response.ok) {
        throw new Error("删除图片失败");
      }

      Toast.showToast("删除成功");
      cb && cb();
    } catch (error) {
      console.error(error);
      Toast.showToast("删除失败");
      throw error;
    }
  }
}
